import axios from 'axios';
import mpAdapter from "axios-miniprogram-adapter";
axios.defaults.adapter = mpAdapter;
import { netConfig } from '@/config/netconfig';
const { baseURL, contentType, requestTimeout, successCode, tokenPrefix } = netConfig;

let tokenLose = true;

const instance = axios.create({
    baseURL,
    timeout: requestTimeout,
    headers: {
        'Content-Type': contentType,
        'Authorization': '',
    },
});

// request interceptor
instance.interceptors.request.use(
    (config) => {
		
        // do something before request is sent
        let token = uni.getStorageSync('ACCESSTOKEN') || uni.getStorageSync('token');
        if (token) {
            config.headers.Authorization = tokenPrefix + token;
        }
        return config;
    },
    (error) => {
		
        // do something with request error
        return Promise.reject(error);
    }
);

// response interceptor
instance.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */
    (response) => {
		
        const res = response.data;
        // 请求出错处理
        if (res.code === -1) {
            tokenLose = false;
            if (res.msg != null)
                uni.showToast({
                    icon: 'none',
                    title: res.msg,
                    duration: 2000
                });

            return Promise.reject(res);
        }
        if (successCode.indexOf(res.status) !== -1) {
            return Promise.reject(res);
        }
        return res;
    },
    (error) => {
		
        if (error.isAxiosError) {
            if (error.response != undefined && error.response.status == 401) {
                uni.removeStorageSync('ACCESSTOKEN');
                var pages = getCurrentPages() // 获取栈实例
                let currentRoute = pages[pages.length - 1].route; //当前页面路径
                if (!(currentRoute == "pages/index/index" || currentRoute == "pages/customerproduct/index")){
                    uni.switchTab({ url: "/pages/index/index" });
                    return;
                }
            } else {
                uni.showToast({
                    icon: 'error',
                    title: '服务异常!',
                    duration: 2000
                });
            }

        }
        return Promise.reject(error);
    }
);

export default instance;